#include "salesstatisticswindow.h"
#include "ui_salesstatisticswindow.h"
#include <QDebug>
#include "mainwindow.h"
#include <QApplication>
#include <QSqlQuery>
#include <QSqlError>

SalesStatisticsWindow::SalesStatisticsWindow(QSqlDatabase db, adminMainWindow *adminmainWindow, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SalesStatisticsWindow),
    m_db(db),
    m_mainWindow(adminmainWindow)
{
    ui->setupUi(this);
    qDebug() << "SalesStatisticsWindow 构造函数执行";
    qDebug() << " SalesStatisticsWindow是否可见（构造函数内）：" << isVisible();

    // 连接“计算销售额”按钮的点击信号到槽函数
    connect(ui->pushButtonCalculate, &QPushButton::clicked, this, &SalesStatisticsWindow::on_pushButtonCalculate_clicked);
}

SalesStatisticsWindow::~SalesStatisticsWindow()
{
    delete ui;
}

void SalesStatisticsWindow::on_pushButtonReturn_clicked()
{
    this->hide();
    if (m_mainWindow) {
        m_mainWindow->show();
    }
}

void SalesStatisticsWindow::on_pushButtonCalculate_clicked()
{
    // 获取用户选择的时间范围
    QDate startDate = ui->dateEditStart->date();
    QDate endDate = ui->dateEditEnd->date();
    QString startStr = startDate.toString("yyyy-MM-dd 00:00:00");
    QString endStr = endDate.toString("yyyy-MM-dd 23:59:59"); // 补全时间，确保覆盖全天

    // 清空表格
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    // ========== 1. 查询总销售额（关联时间范围） ==========
    QSqlQuery totalQuery(m_db);
    totalQuery.prepare(R"(
        SELECT SUM(o.total_price)
        FROM Orders o
        WHERE o.create_time BETWEEN :start AND :end
    )");
    totalQuery.bindValue(":start", startStr);
    totalQuery.bindValue(":end", endStr);

    if (totalQuery.exec() && totalQuery.next()) {
        double totalSales = totalQuery.value(0).toDouble();
        // 插入总销售额行
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem("总销售额"));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(totalSales, 'f', 2)));
    } else {
        qDebug() << "总销售额查询失败:" << totalQuery.lastError().text();
    }

    // ========== 2. 查询各分类销售额（多层关联） ==========
    QSqlQuery categoryQuery(m_db);
    categoryQuery.prepare(R"(
        SELECT
            c.name AS category_name,
            SUM(p.price * od.quantity) AS category_sales
        FROM Orders o
        JOIN OrderDetails od ON o.order_id = od.order_id
        JOIN products p ON od.product_id = p.product_id
        JOIN categories c ON p.category_id = c.category_id
        WHERE o.create_time BETWEEN :start AND :end
        GROUP BY c.category_id
    )");
    categoryQuery.bindValue(":start", startStr);
    categoryQuery.bindValue(":end", endStr);

    if (categoryQuery.exec()) {
        while (categoryQuery.next()) {
            QString category = categoryQuery.value("category_name").toString();
            double sales = categoryQuery.value("category_sales").toDouble();
            // 插入分类销售额行
            int row = ui->tableWidget->rowCount();
            ui->tableWidget->insertRow(row);
            ui->tableWidget->setItem(row, 0, new QTableWidgetItem(category));
            ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(sales, 'f', 2)));
        }
    } else {
        qDebug() << "分类销售额查询失败:" << categoryQuery.lastError().text();
    }
}
